package club.ljwang.security;


import club.ljwang.pojo.User;
import com.qiniu.util.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyUserService implements UserDetailsService {


    private BCryptPasswordEncoder encoder;

    public BCryptPasswordEncoder getEncoder() {
        return encoder;
    }

    public void setEncoder(BCryptPasswordEncoder encoder) {
        this.encoder = encoder;
    }

    //模拟数据库中的用户数据
    public Map<String, User> map = new HashMap<>();
    public void initData(){
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(encoder.encode("admin"));

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(encoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    /**
     * 根据用户名查询用户基本信息（用户名，密码，权限信息）
     * @param username 就是页面输入的账号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
        //1、模拟从数据库查询用户
        User user = map.get(username);
        if(null == user){
            return null;
        }

        //2、查询用户的权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("checkitem_add"));
        if(username.equals("admin")){
            authorities.add(new SimpleGrantedAuthority("checkitem_del"));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }

    public static void main(String[] args) {

        String salt="465131534654654asdfasdfasdfasdfasdf";
        long start = System.currentTimeMillis();
        String pwd = "12345679848941a3sd56f654654as2adfda89"+salt;
        String s = Md5.md5(pwd.getBytes());
        System.out.println("s = " + s);
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end-start));


        long start2 = System.currentTimeMillis();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        String encode = encoder.encode(pwd);
        System.out.println("encode = " + encode);
        long end2 = System.currentTimeMillis();
        System.out.println("time = " + (end2-start2));

    }
}
